package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysTenant;
import com.ruoyi.common.core.domain.entity.SysTenantPackage;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.bo.SysTenantPackageBo;
import com.ruoyi.system.domain.vo.SysTenantPackageVo;
import com.ruoyi.system.mapper.SysTenantPackageMapper;
import com.ruoyi.system.service.ISysTenantPackageService;
import com.ruoyi.system.service.ISysTenantService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 租户套餐Service业务层处理
 *
 * @author ace
 * @date 2022-10-10
 *
 * 避免循环依赖的报错
 */
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
@Service
public class SysTenantPackageServiceImpl implements ISysTenantPackageService {

    private final SysTenantPackageMapper baseMapper;

    private final ISysTenantService tenantService;

    /**
     * 查询租户套餐
     */
    @Override
    public SysTenantPackageVo queryById(Long packageId){
        return baseMapper.selectVoById(packageId);
    }

    /**
     * 查询租户套餐列表
     */
    @Override
    public TableDataInfo<SysTenantPackageVo> queryPageList(SysTenantPackageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysTenantPackage> lqw = buildQueryWrapper(bo);
        Page<SysTenantPackageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询租户套餐列表
     */
    @Override
    public List<SysTenantPackageVo> queryList(SysTenantPackageBo bo) {
        LambdaQueryWrapper<SysTenantPackage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysTenantPackage> buildQueryWrapper(SysTenantPackageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysTenantPackage> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getPackageName()), SysTenantPackage::getPackageName, bo.getPackageName());
        lqw.eq(StringUtils.isNotBlank(bo.getMenuIds()), SysTenantPackage::getMenuIds, bo.getMenuIds());
        return lqw;
    }

    /**
     * 新增租户套餐
     */
    @Override
    public Boolean insertByBo(SysTenantPackageBo bo) {
        SysTenantPackage add = BeanUtil.toBean(bo, SysTenantPackage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPackageId(add.getPackageId());
        }
        return flag;
    }

    /**
     * 修改租户套餐
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysTenantPackageBo bo) {
        SysTenantPackage update = BeanUtil.toBean(bo, SysTenantPackage.class);
        // 校验存在
        SysTenantPackage tenantPackage = validateTenantPackageExists(update.getPackageId());
        validEntityBeforeSave(update);
        // 更新
        boolean flag = baseMapper.updateById(update) > 0;
        // 如果菜单发生变化，则修改每个租户的菜单
        if (!tenantPackage.getMenuIds().equals(update.getMenuIds())) {
            List<SysTenant> tenants = tenantService.getTenantListByPackageId(tenantPackage.getPackageId());
            Set<Long> menuIds = Arrays.stream(update.getMenuIds().split(",")).map(Long::valueOf).collect(Collectors.toSet());
            tenants.forEach(tenant -> tenantService.updateTenantRoleMenu(tenant.getTenantId(), menuIds));
        }
        return  flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysTenantPackage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除租户套餐
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        // 校验正在使用
        ids.forEach(this::validateTenantUsed);
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    private SysTenantPackage validateTenantPackageExists(Long id) {
        SysTenantPackage tenantPackage = baseMapper.selectById(id);
        if (tenantPackage == null) {
            throw new ServiceException("该租户套餐编号:"+id+"不存在");
        }
        return tenantPackage;
    }

    /**
     * 校验租户套餐是否已经被使用
     * @param id
     */
    private void validateTenantUsed(Long id) {
        if(tenantService.getTenantCountByPackageId(id) > 0){
            throw new ServiceException("租户套餐编号:"+id+"已分配，不允许操作");
        }
    }
}
